package org.rency.crawler.common.helper;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.rency.crawler.common.exception.CrawlerIllegalException;

/**
 * 描述: 校验帮助类
 * 最近修改时间:2017/8/30 16:17<br>
 *
 * @author CaiyuRen
 * @version V1.0
 * @since 2017/8/30 16:17
 */
public class ValidatorHelper {

  private static final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

  private ValidatorHelper() {
  }

  public static void notEmpty(String object, String desc) {
    if (StringUtils.isEmpty(object)) {
      throw new CrawlerIllegalException("参数不能为空[" + desc + "]");
    }
  }

  public static void notBlank(String object, String desc) {
    if (StringUtils.isBlank(object)) {
      throw new CrawlerIllegalException("参数不能为空[" + desc + "]");
    }
  }

  public static void notNull(Object object, String desc) {
    if (object == null) {
      throw new CrawlerIllegalException("对象不能为空[" + desc + "]");
    }
  }

  public static void isNull(Object object, String desc) {
    if (object != null) {
      throw new CrawlerIllegalException("对象不能为空[" + desc + "]");
    }
  }

  public static void isTrue(boolean object, String desc) {
    if (!object) {
      throw new CrawlerIllegalException(desc);
    }
  }

  public static void notBlank(String object) {
    ValidatorHelper.notBlank(object, "");
  }

  public static void isNull(Object object) {
    ValidatorHelper.isNull(object, "");
  }

  /**
   * 注解校验
   * <br>Created on 2016年7月19日
   */
  public static <T> void validator(T bean) {
    List<String> errorList = new ArrayList<String>();
    Set<ConstraintViolation<T>> violations = validator.validate(bean);
    if (!violations.isEmpty()) {
      for (ConstraintViolation<T> violation : violations) {
        errorList.add(violation.getMessage());
      }
    }
    ValidatorHelper.isTrue(CollectionUtils.isEmpty(errorList), errorList.toString());
  }

}